<template>
  <el-dialog
    center
    :title="type == 'add' ? '添加' : '编辑'"
    v-model="Visible"
    width="40%"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="dialogForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="热源" prop="heatSourceId">
            <el-select
              v-model="ruleForm.heatSourceId"
              filterable
              clearable
              placeholder="请选择热源"
              style="width:100%;"
              @change="handleSourceChange"
            >
              <el-option
                v-for="item in heatSourceOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="换热站" prop="heatStationId">
            <el-select
              v-model="ruleForm.heatStationId"
              filterable
              clearable
              placeholder="请选择换热站"
              style="width:100%;"
            >
              <el-option
                v-for="item in heatStationOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="系统名称" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="系统编码" prop="code">
            <el-input v-model="ruleForm.code"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="系统别名" prop="shortName">
            <el-input v-model="ruleForm.shortName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户类型" prop="userType">
            <el-select
              v-model="ruleForm.userType"
              filterable
              clearable
              placeholder="请选择用户类型"
              style="width:100%;"
            >
              <el-option
                v-for="item in userTypeOptions"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供热模式" prop="heatingType">
            <el-select
              v-model="ruleForm.heatModel"
              filterable
              clearable
              placeholder="请选择供热模式"
              style="width:100%;"
            >
              <el-option
                v-for="item in heatModelOptions"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="节能类型" prop="heatingType">
            <el-select
              v-model="ruleForm.heatingType"
              filterable
              clearable
              placeholder="请选择节能类型"
              style="width:100%;"
            >
              <el-option
                v-for="item in heatingTypeOptions"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供热面积" prop="heatingArea">
            <el-input v-model="ruleForm.heatingArea"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="低温面积" prop="lowArea">
            <el-input v-model="ruleForm.lowArea"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="经度" prop="longitude">
            <el-input
              v-model="ruleForm.longitude"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纬度" prop="latitude">
            <el-input v-model="ruleForm.latitude" autocomplete="off"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="标签" prop="label">
            <el-tag
              :key="index"
              v-for="(tag, index) in ruleForm.label"
              closable
              style="margin-right: 10px"
              :disable-transitions="false"
              @close="handleTagClose(tag, index)"
            >
              {{ tag }}
            </el-tag>

            <el-input
              class="input-new-tag"
              v-if="inputVisible"
              v-model="inputValue"
              ref="saveTagInput"
              style="width: 100px"
              @keyup.enter="handleInputConfirm"
              @blur="handleInputConfirm"
            >
            </el-input>
            <el-button
              v-else
              class="button-new-tag"
              size="small"
              @click="AddTags"
              >+ 添加</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              v-model="ruleForm.remark"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button
          type="primary"
          v-preventReClick
          @click="submitForm('ruleForm')"
          >确定</el-button
        >
        <el-button @click="handleClose">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script>
import { reactive, toRefs, ref, onMounted, nextTick } from "vue";
import { addSystemList, editSystemList } from "@/api/system";
import { ElMessage } from "element-plus";
import { useStore } from "vuex";
// import { getHeatSourcePermisstion } from "@/api/heatSource";
import { getHeatStation } from "@/api/heatStation";
export default {
  name: "UpdatePassword",
  props: {
    Visible: {
      type: Boolean,
      default: false,
    },
    dialogRow: {
      type: Object,
      default: () => {},
    },
    type: {
      type: String,
      default: "add",
    },
  },
  setup(props, context) {
    const saveTagInput = ref(null);
    const dialogForm = ref(null);
    const store = useStore();
    const validateNum = (rule, value, callback) => {
      if (value == null) {
        callback();
      } else if (!/^[0-9.]*$/.test(value)) {
        callback(new Error("请输入数字类型的值"));
      } else {
        callback();
      }
    };
    const state = reactive({
      inputVisible: false,
      inputValue: "",
      heatModelOptions: [
        "采暖形式",
        // "节能类型",
        "地板采暖",
        "风机盘管",
        "散热器",
      ],
      userTypeOptions: ["公建", "民用", "权属"],
      heatingTypeOptions: [
        "二步节能",
        // "节能类型",
        "老宅",
        "三步节能",
        "四步节能",
      ],
      heatStationOptions: [],
      heatSourceOptions: [],
      ruleForm: {
        heatSourceId: "",
        heatStationId: "",
        name: "",
        code: "",
        userType: "",
        heatModel: "",
        shortName: "",
        heatingType: "",
        heatingArea: 0,
        lowArea: 0,
        longitude: 0,
        latitude: 0,
        label: [],
        sort: 100,
        remark: "",
      },
      rules: {
        name: [{ required: true, message: "请输入系统名称", trigger: "blur" }],
        shortNam: [
          { required: true, message: "请输入系统别名", trigger: "blur" },
        ],
        code: [{ required: true, message: "请输入系统编码", trigger: "blur" }],
        heatingArea: [{ validator: validateNum, trigger: "blur" }],
        lowArea: [{ validator: validateNum, trigger: "blur" }],
        longitude: [{ validator: validateNum, trigger: "blur" }],
        latitude: [{ validator: validateNum, trigger: "blur" }],
      },
    });

    const AddTags = () => {
      state.inputVisible = true;
    };
    const handleTagClose = (tag, index) => {
      state.ruleForm.label.splice(index, 1);
    };
    const handleInputConfirm = () => {
      let inputValue = state.inputValue;
      if (state.ruleForm.label.includes(inputValue)) {
        return ElMessage.error("标签已重复，请重新填写");
      }
      if (inputValue) {
        state.ruleForm.label.push(inputValue);
      }
      state.inputVisible = false;
      state.inputValue = "";
    };

    onMounted(async () => {
      await getHeatSourceList();
      if (props.type == "add") {
        nextTick(() => {
          dialogForm.value.resetFields();
          const { heatStationId, heatSourceId } = props.dialogRow;
          state.ruleForm.heatSourceId = heatSourceId;
          state.ruleForm.heatStationId = heatStationId;
          if (props.dialogRow.heatSourceId) {
            getHeatStationList();
          }
        });
      } else {
        state.ruleForm = props.dialogRow;
      }
    });

    /**热源 */
    const getHeatSourceList = () => {
      state.heatSourceOptions = store.getters.sourceData;
      //   const { data: res } = await getHeatSourcePermisstion();
      //   if (res.success) {
      //     const list = res.data;
      //     state.heatSourceOptions = list;
      //   }
    };
    /**
     * 根据热源选择换热站
     */
    const getHeatStationList = async () => {
      const { data: resp } = await getHeatStation({
        heatSourceId: state.ruleForm.heatSourceId,
      });
      if (resp.success) {
        const list = resp.data;
        state.heatStationOptions = list;
      }
    };

    const handleSourceChange = () => {
      state.ruleForm.heatStationId = "";
      state.heatStationOptions = [];
      getHeatStationList();
    };

    const submitForm = () => {
      dialogForm.value.validate((valid) => {
        if (valid) {
          const {
            heatSourceId,
            heatStationId,
            name,
            code,
            shortName,
            userType,
            heatModel,
            heatingType,
            heatingArea,
            lowArea,
            longitude,
            latitude,
            label,
            sort,
            remark,
          } = state.ruleForm;

          let params = {
            heatSourceId,
            heatStationId,
            name,
            code,
            shortName,
            heatingType,
            userType,
            heatModel,
            heatingArea,
            lowArea,
            longitude,
            latitude,
            label: label.join(","),
            sort,
            remark,
          };

          if (props.type == "add") {
            addSystemList(params).then((res) => {
              if (res.data.success) {
                ElMessage.success(res.data.msg);
                handleClose();
                dialogForm.value.resetFields();
                context.emit("refresh");
              }
            });
          } else {
            params.id = state.ruleForm.id;
            editSystemList(params).then((res) => {
              if (res.data.success) {
                ElMessage.success(res.data.msg);
                handleClose();
                context.emit("refresh");
              }
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    };

    const handleClose = () => {
      context.emit("close", false);
    };

    return {
      ...toRefs(state),
      saveTagInput,
      AddTags,
      submitForm,
      dialogForm,
      handleClose,
      handleInputConfirm,
      handleTagClose,
      handleSourceChange,
    };
  },
};
</script>
